import { ChangeMemberMenuParams, UserListReturnType } from "@Tea/model"
import { TokenObj } from "../dao/Token"
import { renderSelectSql } from "../utils/renderSql"
import { ReposBase } from "./RepoBase"
export type MenuItemType = {
  menuId: number,
  code: string,
  title: string,
  pMenuId: number | null
}
export class UserMenuRepository extends ReposBase {
  public static inst = new UserMenuRepository()
  public static getInstance() {
    return UserMenuRepository.inst
  }

  // 通过缓存token中的 userid 获取user的菜单
  getUserMenu(userId: TokenObj["userId"]) {
    const sql = renderSelectSql({
      database: [ { name: "user_menus", aliasName: "um" }, { name: "menus", aliasName: "m" }],
      "where": [
        { key: "user_id", sqlVal: userId },
        { key: "um.menu_id", sqlVal: "m.menu_id", isDatabase: true },
        { key: "m.enable",sqlVal: 1}
      ],
      returnFeild: [
        { name: "menu_id", aliasName: "menuId", dbName: "user_menus" },
        "code",
        "title",
        { name: "p_menu_id", aliasName: "pMenuId" }
      ],
      otherSql:"ORDER BY p_menu_id, menu_index"
    })
    console.log(sql);
    
    return this.query<MenuItemType>(sql)
  }

  // 通过 id 获取 成员的菜单
  getUserMenuIdById(userId: UserListReturnType["userId"]) {
    const sql = `SELECT menu_id menuId FROM user_menus WHERE user_id=${userId}`

    return this.query<{menuId:MenuItemType["menuId"]}>(sql)
  }

  // 删除用户的所有信息
  deleteUserAllMenu(userId: UserListReturnType["userId"]) {
    const sql = `DELETE FROM user_menus WHERE user_id = ${userId}`

    return this.delete(sql)
  }

  // 添加用户的菜单
  addUserMenu(params: ChangeMemberMenuParams, handerId: TokenObj["userId"]) {
    const promise = [] as ReturnType<typeof this.insert>[]

    params.menuIds.forEach((menuId) => {
      promise.push(this.insert(`INSERT INTO user_menus (user_id,menu_id,hander_id,hander_time) VALUES (${params.userId},${menuId},${handerId},NOW());`))
    })

    return Promise.all(promise)
  }
}